package com.bilibili.server.service;

import com.bilibili.server.entity.VideoType;
import com.bilibili.server.repository.VideoTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class VideoTypeService {
    @Autowired
    private VideoTypeRepository videoTypeRepository;

    // 获取所有视频类型
    public List<VideoType> getAllVideoTypes() {
        return videoTypeRepository.findByTypeStatus(1);
    }

    // 根据ID获取视频类型详情
    public VideoType getVideoTypeById(int typeId) {
        Optional<VideoType> videoTypeOptional = videoTypeRepository.findById(typeId);
        return videoTypeOptional.orElse(null);
    }

    // 创建新视频类型
    public VideoType createVideoType(VideoType videoType) {
        // 检查类型名称是否已存在
        Optional<VideoType> existingType = videoTypeRepository.findByTypeName(videoType.getTypeName());
        if (existingType.isPresent()) {
            throw new RuntimeException("视频类型名称已存在");
        }

        // 检查类型别名是否已存在
        if (videoType.getTypeAlias() != null) {
            Optional<VideoType> existingAlias = videoTypeRepository.findByTypeAlias(videoType.getTypeAlias());
            if (existingAlias.isPresent()) {
                throw new RuntimeException("视频类型别名已存在");
            }
        }

        return videoTypeRepository.save(videoType);
    }

    // 更新视频类型
    public VideoType updateVideoType(int typeId, VideoType videoType) {
        Optional<VideoType> videoTypeOptional = videoTypeRepository.findById(typeId);
        if (videoTypeOptional.isPresent()) {
            VideoType existingType = videoTypeOptional.get();
            
            // 检查类型名称是否已存在（排除当前类型）
            Optional<VideoType> existingTypeName = videoTypeRepository.findByTypeName(videoType.getTypeName());
            if (existingTypeName.isPresent() && existingTypeName.get().getId() != typeId) {
                throw new RuntimeException("视频类型名称已存在");
            }

            // 检查类型别名是否已存在（排除当前类型）
            if (videoType.getTypeAlias() != null) {
                Optional<VideoType> existingTypeAlias = videoTypeRepository.findByTypeAlias(videoType.getTypeAlias());
                if (existingTypeAlias.isPresent() && existingTypeAlias.get().getId() != typeId) {
                    throw new RuntimeException("视频类型别名已存在");
                }
            }

            // 更新视频类型信息
            existingType.setTypeName(videoType.getTypeName());
            existingType.setTypeAlias(videoType.getTypeAlias());
            existingType.setTypeDescription(videoType.getTypeDescription());
            existingType.setTypeStatus(videoType.getTypeStatus());
            return videoTypeRepository.save(existingType);
        }
        return null;
    }

    // 删除视频类型
    public void deleteVideoType(int typeId) {
        videoTypeRepository.deleteById(typeId);
    }
}